<?php
class BookModel {
    private $book_db;

    public static function encryptId($id) {
        $num = ConfigParserLib::get('book', 'using_sid_key_num');
        $keys = ConfigParserLib::get('book', 'sid_keys');
        $key = $keys[$num];
        $encrypted_text = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $id, MCRYPT_MODE_ECB);
        return $num . bin2hex($encrypted_text);
    }

    public static function decryptSid($sid) {
        $num = substr($sid, 0, 1);
        $keys = ConfigParserLib::get('book', 'sid_keys');
        $key = $keys[$num];
        return intval(mcrypt_decrypt(MCRYPT_BLOWFISH, $key, hex2bin(substr($sid, 1)), MCRYPT_MODE_ECB));
    }
    
    public function __construct() {
        $this->book_db = new BookDb();
    }

    public function add($data) {
        $data['create_time'] = time();
        return $this->book_db->insertRow($data);
    }

    public function getList($input) {
        $where = 1;
        $column = array('name', 'author', 'id', 'create_time');
        $order_by = 'create_time desc';
        $r = $this->book_db->selectRows($where, $column, 0, '', '', $order_by);
        $data = array();
        foreach($r as $one) {
            $one['sid'] = self::encryptId($one['id']);
            unset($one['id']);
            $data[] = $one;
        }
        return $data;
    }

    public function getBySid($sid) {
        $where = array(
            'id' => self::decryptSid($sid),
        );
        $r = $this->book_db->selectRow($where);
        $r['sid'] = $sid;
        return $r;
    }
}
?>
